class Order < ActiveRecord::Base
  before_create :generate_token
  after_create  :create_shipment, :create_payment

  has_many :order_items
  has_many :comments, :foreign_key => :commentable_id

  has_one :shipment
  has_one :shipping_address, :through => :shipment, :foreign_key => "order_shipping_address_id"
  
  has_one :payment
  has_one :billing_address, :through => :payment

  has_one :order_company

  acts_as_commentable

  accepts_nested_attributes_for :order_items, :allow_destroy => true#, :reject_if =>
  accepts_nested_attributes_for :shipping_address
  accepts_nested_attributes_for :billing_address
  accepts_nested_attributes_for :comments, :allow_destroy => true, :reject_if => proc {|attr| attr['comment'].blank?}

  def self.order_completed
    where('orders.state NOT IN ("in_progress")')
  end

  def order_completed?
    !!completed_at
  end

  def generate_token
    self.token = Authlogic::Random.friendly_token
  end

  def create_shipment
    shipping_method = ShippingMethod.first
    self.shipment = Shipment.create({:order => self, :shipping_method_id => shipping_method.id, :cost => shipping_method.price})
  end

  def create_payment
    
  end

  def whole_name
    self.user_name + " " + self.user_surname
  end
end
